import java.io.*;
import java.net.*;

public class Server {

	public static void main(String[] args) throws Exception {
		// 监听5600端口
		ServerSocket serverSocket = new ServerSocket(5600);
		while (true) {
			Socket s = serverSocket.accept();
			System.out.println("Receving a file");
			new Thread(new ServerThread(s)).start();
		}
	}
}

class ServerThread implements Runnable {
	private Socket socket;

	public ServerThread(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		try {
			// 创建存放文件的目录
			File parentFile = new File("C:\\upload\\");
			if (!parentFile.exists()) {
				parentFile.mkdir();
			}
			// 接收文件
			InputStream in = socket.getInputStream();
			byte[] buf = new byte[1024];
			int len = in.read(buf);

			boolean flag = false; // 标记是否已经接收到文件名和格式
			File file = null;
			FileOutputStream fos = null;
			int off = 0;
			while (true) {
				if (len == -1) {
					break;
				}
				if (flag == false) {
					// 寻找文件名并将其从数据流分割出来
					int spiltIndex = new String(buf, 0, len).indexOf('|');
					if (spiltIndex != -1) {
						// 将文件名单独分隔出来
						String fileName = new String(buf, 0, len).substring(0, spiltIndex);
						// 将文件名从数据流中剔除
						int tempLen = len;
						off = (fileName + "|").getBytes().length;
						len = tempLen - off;
						// 用文件名创建文件对象
						file = new File(parentFile, fileName);
						fos = new FileOutputStream(file);
						flag = true;
					}
				}
				// 将数据写入本地文件
				fos.write(buf, off, len);
				off = 0;
				len = in.read(buf);
			}
			// 告诉客户端传输成功
			OutputStream out = socket.getOutputStream();
			out.write("Upload successful".getBytes());
			System.out.println("Receve end");
			// 关闭流
			in.close();
			fos.close();
			out.close();
			socket.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}